package vashion.azeroth.core.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vashion.azeroth.contant.ApprovalErrorEnum;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.ExperienceErrorEnum;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.PublishFilesErrorEnum;
import vashion.azeroth.contant.experience.ExperienceValue;
import vashion.azeroth.core.manager.personal.PersonalApprovalManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.manager.personal.PersonalPublishFilesManager;
import vashion.azeroth.core.personal.pojo.FeedTag;
import vashion.azeroth.core.personal.pojo.PersonalApproval;
import vashion.azeroth.core.personal.pojo.PersonalExperience;
import vashion.azeroth.core.personal.pojo.PersonalFeed;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.pojo.PersonalPublishFiles;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.PersonalApprovalService;
import vashion.azeroth.core.service.PersonalExperienceService;
import vashion.azeroth.core.service.PersonalMemberService;

import com.alibaba.druid.util.StringUtils;

@Service
public class PersonalApprovalServiceImpl<T> implements
		PersonalApprovalService<T> {

	private final static Logger log = LoggerFactory
			.getLogger(PersonalApprovalServiceImpl.class);

	@Autowired
	PersonalApprovalManager personalApprovalManager;

	@Autowired
	PersonalMemberManager personalMemberManager;

	@Autowired
	PersonalMemberService personalMemberService;

	@Autowired
	PersonalPublishFilesManager personalPublishFilesManager;
	
	@Autowired
	private PersonalExperienceService<T> personalExperienceService;

	@Override
	public ApiResult<Boolean> addApproval(PersonalApproval personalApproval) {

		ApiResult<Boolean> result = validParam(personalApproval);

		// 参数不合法，直接返回
		if (!result.isSuccess()) {

			return result;
		}

		try {

			// 默认状态设置为 NORMAL
			personalApproval
					.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

			// 先查询关联关系

			int cnt = personalApprovalManager.findCnt(personalApproval);

			if (cnt >= 1) {

				return ApiResult
						.newErrorResult(
								ApprovalErrorEnum.APPROVAL_ALREADY_EXIST
										.getErrorCode(),
								ApprovalErrorEnum.APPROVAL_ALREADY_EXIST
										.getErrorMessage(), false);
			}

			// 补合参数
			fillParam(personalApproval);

			// 添加时间参数
			Date d = new Date();
			personalApproval.setTimeAdd(d);
			personalApproval.setTimeEdit(d);

			PersonalApproval addApiResult = personalApprovalManager
					.save(personalApproval);

			// 更新贴子点赞数量操作
			String appFlag = "add";
			updateFeed(personalApproval, appFlag);
			
				return ApiResult.newSuccessResult(true);
		} catch (Exception e) {

			log.error(e.getMessage());

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}

	}

	@Override
	public ApiResult<Boolean> cancelApproval(PersonalApproval personalApproval) {

		ApiResult<Boolean> result = validParam(personalApproval);

		// 参数不合法，直接返回
		if (!result.isSuccess()) {

			return result;

		}

		try {

			personalApproval
					.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

			// 先查询关联关系

			List<PersonalApproval> resultList = personalApprovalManager
					.find(personalApproval);

			if (resultList.size() == 0) {

				return ApiResult
						.newErrorResult(ApprovalErrorEnum.NOT_APPROVAL
								.getErrorCode(), ApprovalErrorEnum.NOT_APPROVAL
								.getErrorMessage(), false);
			}

			// 取消点赞
			resultList
					.get(0)
					.setStatus(
							AzerothConstants.PersonalApproval.PersonalApprovalStatus.DELETE);

			resultList.get(0).setTimeEdit(new Date());

			personalApprovalManager.updateById(resultList.get(0));

			// 更新贴子点赞数量操作
			String appFlag = "delete";
			updateFeed(personalApproval, appFlag);

			return ApiResult.newSuccessResult(true);

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}

	}

	@Override
	public ApiResult<List<PersonalApproval>> queryMyApprovalItem(
			Long memberId, int pageNo, int pageSize) {

		ApiResult<List<PersonalApproval>> ApiResult = new ApiResult();

		if (memberId == null || memberId <= 0) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.INVALID_PARAMETER.getErrorCode(),
					GenericErrorEnum.INVALID_PARAMETER.getErrorMessage());

		}

		// 构造参数
		PersonalApproval pf = new PersonalApproval();

		pf.setMemberId(memberId);

		pf.setFirstRow(pageNo);

		pf.setPageSize(pageSize);

		pf.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

		pf.setType(AzerothConstants.PersonalFavtories.PersonalFavtoriesType.ITEM);

		try {

			int totalCount = personalApprovalManager.findCnt(pf);

			List<PersonalApproval> data = personalApprovalManager.find(pf);

			return ApiResult.newSuccessResult(data, totalCount);

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	@Override
	public ApiResult<List<PersonalApproval>> queryMyApprovalPost(
			Long memberId, int pageNo, int pageSize) {

		if (memberId == null || memberId <= 0) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.INVALID_PARAMETER.getErrorCode(),
					GenericErrorEnum.INVALID_PARAMETER.getErrorMessage());

		}

		// 构造参数
		PersonalApproval pf = new PersonalApproval();

		pf.setMemberId(memberId);

		pf.setFirstRow(pageNo);

		pf.setPageSize(pageSize);

		pf.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

		pf.setType(AzerothConstants.PersonalFavtories.PersonalFavtoriesType.POST);

		try {

			int totalCount = personalApprovalManager.findCnt(pf);

			List<PersonalApproval> data = personalApprovalManager.find(pf);

			return ApiResult.newSuccessResult(data, totalCount);

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	@Override
	public ApiResult<Boolean> queryIsApproval(Long memberId, Integer type,
			String targetCode) {

		ApiResult<ArrayList<PersonalFeed>> result = new ApiResult<ArrayList<PersonalFeed>>();
		if (memberId == null || memberId <= 0) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "会员ID"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);

		}
		if (null == type) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);
		}

		if (!AzerothConstants.PersonalFavtories.PersonalFavtoriesType.ITEM
				.equals(type)
				&& !AzerothConstants.PersonalFavtories.PersonalFavtoriesType.POST
						.equals(type)) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EXIST.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EXIST.getErrorMessage(),
					false);
		}

		if (StringUtils.isEmpty(targetCode) || "".equals(targetCode.trim())) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "商品/贴子编码"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);
		}

		// 构造参数
		PersonalApproval pf = new PersonalApproval();

		pf.setMemberId(memberId);

		pf.setType(type);

		pf.setTargetCode(targetCode);

		pf.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

		try {

			List<PersonalApproval> data = personalApprovalManager.find(pf);

			if (data.size() > 0) {

				return ApiResult.newSuccessResult(true);
			} else {

				return ApiResult.newSuccessResult(false);

			}

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	@Override
	public ApiResult<List<PersonalApproval>> getFeedsApprovalInfo(Integer type,
			String targetCode) {

		ApiResult<List<PersonalApproval>> result = new ApiResult<List<PersonalApproval>>();
		// if (memberId == null || memberId <= 0) {
		//
		// return ApiResult.newErrorResult(
		// GenericErrorEnum.NOT_EMPTY.getErrorCode(), "会员ID"
		// + GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
		// false);
		//
		// }
		if (null == type) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (StringUtils.isEmpty(targetCode) || "".equals(targetCode.trim())) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "商品/贴子编码"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage());

		}

		// 构造参数
		PersonalApproval pf = new PersonalApproval();

		pf.setType(type);

		pf.setTargetCode(targetCode);

		pf.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

		try {

			List<PersonalApproval> paList = personalApprovalManager
					.getFeedsApprovalInfo(pf);

			if (paList.size() > 0) {

				return ApiResult.newSuccessResult(paList);
			} else {
				return ApiResult.newErrorResult(
						PublishFilesErrorEnum.FEED_APPROVAL_CNT.getErrorCode(),
						PublishFilesErrorEnum.FEED_APPROVAL_CNT
								.getErrorMessage());

			}

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	public ApiResult<Integer> queryApprovalCnt(Integer type, String targetCode) {

		if (StringUtils.isEmpty(targetCode)) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "商品/贴子编码"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (null == type) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (!AzerothConstants.PersonalFavtories.PersonalFavtoriesType.ITEM
				.equals(type)
				&& !AzerothConstants.PersonalFavtories.PersonalFavtoriesType.POST
						.equals(type)) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EXIST.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		// 构造参数
		PersonalApproval pa = new PersonalApproval();

		pa.setType(type);

		pa.setTargetCode(targetCode);

		pa.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

		try {

			int cnt = personalApprovalManager.findCnt(pa);

			return ApiResult.newSuccessResult(cnt);

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	// 校验参合法性，不合法返FALSE
	private ApiResult<Boolean> validParam(PersonalApproval personalApproval) {

		if (null == personalApproval.getMemberId()) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "会员ID"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);
		}

		// if (StringUtils.isEmpty(personalApproval.getMemberName())) {
		//
		// return ApiResult.newErrorResult(
		// GenericErrorEnum.NOT_EMPTY.getErrorCode(), "会员名称"
		// + GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
		// false);
		// }

		if (null == personalApproval.getApprovalMemberId()) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "点赞者ID"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);

		}

		// if (StringUtils.isEmpty(personalApproval.getApprovalMemberName())) {
		//
		// return ApiResult.newErrorResult(
		// GenericErrorEnum.NOT_EMPTY.getErrorCode(), "点赞者名称"
		// + GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
		// false);
		// }

		if (StringUtils.isEmpty(personalApproval.getTargetCode())) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "商品/贴子编码"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);
		}

		if (null == personalApproval.getType()) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);
		}

		if (!AzerothConstants.PersonalFavtories.PersonalFavtoriesType.ITEM
				.equals(personalApproval.getType())
				&& !AzerothConstants.PersonalFavtories.PersonalFavtoriesType.POST
						.equals(personalApproval.getType())) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EXIST.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EXIST.getErrorMessage(),
					false);
		}

		Long memberId = personalApproval.getMemberId();

		String memberName = personalApproval.getMemberName();

		ApiResult<Boolean> result = checkMemberExist(memberId, memberName);

		if (!result.isSuccess()) {

			return result;
		}

		Long approvalMemberId = personalApproval.getApprovalMemberId();

		String approvalMemberName = personalApproval.getApprovalMemberName();

		if (!result.isSuccess()) {

			return result;
		}

		return ApiResult.newSuccessResult(true);

	}

	public ApiResult<List<PersonalMember>> queryApprovalMember(Integer type,
			String targetCode) {

		if (StringUtils.isEmpty(targetCode)) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "商品/贴子编码"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (null == type) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (!AzerothConstants.PersonalFavtories.PersonalFavtoriesType.ITEM
				.equals(type)
				&& !AzerothConstants.PersonalFavtories.PersonalFavtoriesType.POST
						.equals(type)) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EXIST.getErrorCode(), "类型"
							+ GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}

		// 构造参数
		PersonalApproval pa = new PersonalApproval();

		pa.setType(type);

		pa.setTargetCode(targetCode);

		pa.setStatus(AzerothConstants.PersonalApproval.PersonalApprovalStatus.NORMAL);

		try {

			List<PersonalApproval> personalApprovalList = personalApprovalManager
					.find(pa);

			List<PersonalMember> personalMemberList = new ArrayList<PersonalMember>();

			for (PersonalApproval per : personalApprovalList) {

				Long memberId = per.getApprovalMemberId();

				PersonalMember pm = personalMemberManager.get(memberId);

				personalMemberList.add(pm);

			}

			return ApiResult.newSuccessResult(personalMemberList);

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	public ApiResult<Boolean> checkMemberExist(Long memberId,
			String memberName) {

		PersonalMember personalMember = new PersonalMember();

		personalMember.setMemberId(memberId);

		personalMember.setMemberName(memberName);

		ApiResult<PersonalMember> result = personalMemberService
				.checkMember(personalMember);

		if (result.isSuccess()) {
			return ApiResult.newSuccessResult();
		} else {

			return ApiResult.newErrorResult(result.getErrorCode(),
					result.getErrorMsg(), false);
		}

	}

	public void fillParam(PersonalApproval personalApproval) {

		Long memberId = personalApproval.getMemberId();

		Long approvalMemberId = personalApproval.getApprovalMemberId();

		PersonalMember personalMember = personalMemberManager.get(memberId);

		if (personalMember != null) {

			personalApproval.setMemberName(personalMember.getMemberName());
		}

		personalMember = personalMemberManager.get(approvalMemberId);

		if (personalMember != null) {

			personalApproval.setApprovalMemberName(personalMember
					.getMemberName());
		}

	}

	public void updateFeed(PersonalApproval personalApproval, String appFlag) {

		if (personalApproval.getType().equals(
				AzerothConstants.PersonalFavtories.PersonalFavtoriesType.POST)) {

			PersonalPublishFiles personalPublishFiles = new PersonalPublishFiles();

			Integer count = queryApprovalCnt(personalApproval.getType(), personalApproval.getTargetCode()).getData();

			personalPublishFiles.setApprovalCount(count);

			Long publishFileId = Long.valueOf(personalApproval
					.getTargetCode());

			personalPublishFiles.setPublishFileId(publishFileId);
			

			personalPublishFilesManager.update(personalPublishFiles);

			PersonalPublishFiles feed = personalPublishFilesManager.get(publishFileId);
			PersonalExperience experience = new PersonalExperience();
//			点赞帖子，经验base值加1, 取消点赞经验base值减一
			if (appFlag.equals("add")) {
				experience.setValueBase(ExperienceValue.FEED_APPROVE_UP.getCode());
			}
			if (appFlag.equals("delete")) {
				experience.setValueBase(ExperienceValue.FEED_APPROVE_DOWN.getCode());
			}
			experience.setMemberId(feed.getMemberId());
			try {
				ApiResult<Integer> expRes = personalExperienceService.updateExperienceBase(experience);
				log.info("帖子发布者更新后经验值为： " + expRes.getData());
			} catch (Exception e) {
				log.error("更新帖子发布者经验值失败" + e);
			}
		}

	}

}
